import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入相应的组件
import Layout from '@/views/Layout'
import AboutPage from '@/views/AboutPage'
import Login from '@/views/Login'
import Home from '@/views/HomePage'
import Menu from '@/views/Menu'
import ErrorPage from '@/views/ErrorPage'
import AddMenusItem from '@/views/Menu/AddMenusItem'


Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: '',
    component: Layout,
    meta: {
      isAuth: true  // 有权限才能访问
    },
    children: [
      {
        path: '',
        name: 'home',
        // 也可以这么导入组件
        component: Home,
        meta: {
          isAuth: true  // 有权限才能访问
        }
      },
      {
        path: 'about',
        name: 'about',
        component: AboutPage,
        meta: {
          isAuth: true  // 有权限才能访问
        }
      },
      {
        path: '/menu',
        name: 'menu',
        component: Menu,
        meta: {
          isAuth: true
        }
      },
      {
        path: '/menus/addmenusitem',
        name: 'addmenusitem',
        component: AddMenusItem,
        meta: {
          isAuth: true
        }
      },
      {
        path: '/menus/:id/edit',
        name: 'menus_edit',
        component: AddMenusItem,
        meta: {
          isAuth: true
        }
      }
    ]
  },
  {
    path: "/login",
    name: 'login',
    component: Login,
    meta: {
      isAuth: false  // 有权限才能访问
    }
  },
  {
    // * 的意思是，匹配所有的路径
    path: '*',
    name: 'errorpage',
    component: ErrorPage
  }
]

const router = new VueRouter({
  routes
})

// 全局前置守卫：每次路由切换前执行
router.beforeEach((to, from, next) => {
  // 判断每次访问前是否需要权限（需要返回true，否则返回false）
  if (to.matched.some(arr => arr.meta.isAuth)) {
    // 再判断有没有token值（如果有next，否则跳转到login页面）
    // 有token值
    if (localStorage.getItem('tokenInfo')) {
      next()
    } else {
      // 没有token，直接跳转到登录页面
      next({
        name: 'login'
      })
    }
  } else {
    // 放行
    next()
  }
})

export default router
